package com.example.memoplus.ui;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.example.memoplus.R;
import com.example.memoplus.data.Memo;
import com.example.memoplus.data.MemoRepository;
import com.example.memoplus.util.DateUtils;

import java.util.Date;

public class EditMemoActivity extends AppCompatActivity implements View.OnClickListener{

    private static final String TAG = "EditMemoActivity";
    private Memo memo;
    private EditText editTextContent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_memo);

        // 监听
        editTextContent = (EditText) findViewById(R.id.et_content);
        findViewById(R.id.ib_save).setOnClickListener(this);
        findViewById(R.id.ib_cancel).setOnClickListener(this);



        Intent intent = getIntent();
        // 获取 intent 中的数据
        if (intent != null && intent.hasExtra("memo")) {
            memo = (Memo) intent.getSerializableExtra("memo");
            editTextContent.setText(memo.getContent());  // 回显文本内容
            editTextContent.setSelection(memo.getContent().length());  // 光标自动移动到文本尾部
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.ib_save) {        // 保存
            // 判断 memo 是否为空，为空则表示新增，否则为修改
            if (memo == null) {
                memo = new Memo();
                Date creationTime = new Date();
                memo.setContent(editTextContent.getText().toString());
                memo.setCreationTime(DateUtils.formatDate(creationTime));
                MemoRepository.insertMemo(memo);
            } else {
                memo.setContent(editTextContent.getText().toString());
                MemoRepository.updateMemoById(memo);
            }

            finish();
        } else if (v.getId() == R.id.ib_cancel) {
            finish();       // 退出
        }
    }
}